<template>
    <div class="divCommon w-full bg-white  shadow-md rounded-lg p-6  transition-transform duration-300">
        <n-space class="controls">
            <p class='cursor-pointer :hover' @click="expandAll">
                展开全部
            </p>
            <p class='cursor-pointer' @click="collapseAll">
                收起全部
            </p>
        </n-space>

        <n-tree ref="tree" class="mt-3" block-line :data="showData" :expanded-keys="expandedKeys" key-field="key"
            @update:expanded-keys="handleExpand" :node-props="nodeProp" />
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { NTree, NSpace } from 'naive-ui'
import { getArticleTree } from '@/api/article'
import { AsyncTaskHandler } from '@/utils/asyncTaskHandler'
import { useRouter } from 'vue-router';
import type { TreeOption } from 'naive-ui'
const $router = useRouter()
interface ArticleTreeListVO {
    tag: string;
    children: ArticleTreeVO[];
}

interface ArticleTreeVO {
    articleId: number;
    title: string;
}

interface TreeNode {
    label: string;
    key: string;
    children?: TreeNode[];
}

onMounted(() => {
    treeList()
})
const tree = ref(null)
let showData = ref<TreeNode[]>([]);
function transformData(sourceData: ArticleTreeListVO[]) {
    // 清空 showData
    showData.value = [];
    // 遍历原始数据中的每个标签项
    for (let i = 0; i < sourceData.length; i++) {
        // 获取当前标签对象
        let tagItem = sourceData[i];
        // 创建新结构的根节点对象
        let treeNode: TreeNode = {
            label: tagItem.tag, // 标签名称作为label
            key: 0 + i.toString(), // 使用标签索引作为key
            children: [] // 初始化子节点列表
        };
        // 遍历该标签下的所有文章
        tagItem.children.forEach(article => {
            // 为每个文章创建子节点对象
            let childNode: TreeNode = {
                label: article.title, // 文章标题作为label
                key: article.articleId.toString(), // 文章ID作为key
            };
            // 将子节点添加到根节点的children中
            treeNode.children?.push(childNode);
        });
        // 将根节点添加到showData中
        showData.value.push(treeNode);
    }
}
// 点击
const nodeProp = ({ option }: { option: TreeOption }) => {
    // 阻止第一个的行为
    if (option?.children) {
        return {};
    }
    return {
        onClick() { 
            $router.push({ path: '/articleDetail', query: { id: option.key } })
        }
    }
}

const treeList = async () => {
    let res = await AsyncTaskHandler.handleSingleTask(getArticleTree())
    transformData(res.data)
}
// 展开的节点keys
const expandedKeys = ref([])

// 递归获取所有节点key
const getAllKeys = (nodes: any) => {
    return nodes.reduce((keys: any, node: any) => {
        keys.push(node.key)
        if (node.children) keys.push(...getAllKeys(node.children))
        return keys
    }, [])
}

// 展开全部
const expandAll = () => {
    expandedKeys.value = getAllKeys(showData.value)
}

// 收起全部
const collapseAll = () => {
    expandedKeys.value = []
}

// 处理展开状态变化
const handleExpand = (keys: any) => {
    expandedKeys.value = keys
}
</script>

<style scoped>
p:hover {
    color: var(--common-color);
}

:deep(.n-tree) {
    --n-node-color-active: var(--common-color) !important;
}
</style>